// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin.unit.compiler;

import java.io.File;
import java.io.FileReader;

import org.apache.commons.io.IOUtils;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class UnitLoaderImpl implements UnitLoader {

  private final UnitParser unitParser;
  private final String[] sourcePaths;

  public UnitLoaderImpl(UnitParser unitParser, String[] sourcePaths) {
    this.unitParser = unitParser;
    this.sourcePaths = sourcePaths;
  }
  
  public Unit loadUnit(String unitName) throws Exception {
    String path = findPath(unitName);
    
    FileReader reader = new FileReader(path);
    try {
      return unitParser.parse(IOUtils.toString(reader));
    } finally {
      reader.close();
    }
  }
  
  private String findPath(String unitName) throws Exception {
    String baseUnitPath = unitName.replace('.', '/') + ".java";
    
    File file = new File(baseUnitPath);
    if (file.exists()) return baseUnitPath;
    
    for (String sourcePath : sourcePaths) {
      if (!sourcePath.endsWith("/")) sourcePath = sourcePath + "/";
      String unitPath = sourcePath + baseUnitPath;
      file = new File(unitPath);
      if (file.exists()) return unitPath; 
    }
    
    throw new Exception("Could not find " + unitName);
  }
}
